<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import {
  ListOption,
  Secret,
  SecretType
} from "@/views/domain/kubeHud/api/k8s/types";
import { useK8SApi } from "@/views/domain/kubeHud/api/k8s/k8s";
import { objectToString } from "@/views/domain/kubeHud/utils";

const { secretRepo } = useK8SApi();

type Prop = {
  type?: SecretType;
  namespace?: string;
};

const props = defineProps<Prop>();
const model = defineModel<string>();

const secretList = ref<Secret[]>([]);

const loadSecretList = async () => {
  const query = {
    type: props.type
  };

  const list = await secretRepo.getSecret({
    namespace: props.namespace,
    fieldSelector: objectToString(query)
  });

  secretList.value = list?.items;
};
const activeSecretText = computed(() => {
  const secret = secretList.value.find(
    secret => secret.metadata.name === model.value
  );
  if (!secret) {
    return "";
  }

  switch (secret.type) {
    case SecretType.BasicAuth:
      return `${secret.data.username}(${secret.metadata.name})`;
    case SecretType.DockerConfigJson:
      return `${secret.metadata.name}`;
    default:
      return secret.metadata.name;
  }
});

onMounted(() => {
  loadSecretList();
});
</script>

<template>
  <el-select v-model="model">
    <el-option
      v-for="secret in secretList"
      :key="secret.metadata.name"
      :label="secret.metadata.name"
      :value="secret.metadata.name"
    />

    <template #label>
      <span>{{ activeSecretText }}</span>
    </template>
  </el-select>
</template>
<style lang="scss" scoped></style>
